import type { JianShuElements } from '../../../../../../types/constants'
import type { ThemeType } from '../../../../../../types/interfaces'
import { BlogThemeService } from '../../../../../../lib/abstract'
import {
  AppStyleCollections,
  BODY_SELECTOR,
  generateHideSelector,
  PLATFORM_PAGE_TYPES,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../types/constants'

export class JianShuThemeService extends BlogThemeService {
  readonly name = 'jianShuTheme'
  readonly platformPageType: string = PLATFORM_PAGE_TYPES.BLOG.value
  private static instance: JianShuThemeService
  declare readonly elements: JianShuElements
  readonly wrapperSelector: string = BODY_SELECTOR

  constructor() {
    super(SUPPORTED_PLATFORMS.JIAN_SHU)

    this.checkEnv()
    this.initExcludedTitleElementsSelectors(this.excludedTitleElementsSelectors)
    this.updateElementStylesForTheme()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): JianShuThemeService {
    if (!JianShuThemeService.instance) {
      JianShuThemeService.instance = new JianShuThemeService()
    }
    return JianShuThemeService.instance
  }

  updateElementStylesForTheme(): void {
    // 没有页眉时移除文章上边距（用样式没有生效，所以这里用 js 来处理，很奇怪！！！）
    document.querySelectorAll(`${BODY_SELECTOR} #__next:has(> header.${AppStyleCollections.Hide.AD}) div[role="main"]`).forEach((el) => {
      (el as HTMLElement).style.setProperty('padding-top', '0', 'important')
    })
  }

  platformStyleVar(_theme: ThemeType): string {
    return ``
  }

  getPageStyles(_theme: ThemeType): string {
    return `
${BODY_SELECTOR} #__next {
  /* 没有页眉时移除文章上边距 */
  &:has(${generateHideSelector('> header')}) div[role="main"] {
    padding-top: 0 !important;
  }

  > div:has(article) {
    background: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  }
}
`
  }

  getMainStyles(_theme: ThemeType): string {
    return `
/* 文章审核中或不存在时的样式 */    
[data-page-element="empty-container"] {
  z-index: 10 !important;
  background-color: transparent !important;
}
/* 文章标题 */
[data-page-element="content-container"] > h2 {
  color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
}
`
  }

  getPatchedStyles(_theme: ThemeType): string {
    return ``
  }

  getFixedStyles(_theme: ThemeType): string {
    return ``
  }

  customImageStyles(theme: ThemeType): string {
    const { INFO_CONTAINER } = this.elements

    let profileStyle = ''
    if (INFO_CONTAINER && INFO_CONTAINER.selector !== '' && theme === 'dark') {
      profileStyle = `
${INFO_CONTAINER.selector} :is(img, button) {
  /* 调整资料图片 */
  filter: brightness(0.8) contrast(1.0);
}
`
    }
    return profileStyle
  }
}
